package com.levi.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.RequestDispatcher;

@Controller
public class ShiroController {

    @RequestMapping({"/", "/index"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "helo,shiro");
        return "index";
    }

    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "/login";
    }

    @RequestMapping("/user/add")
    @RequiresPermissions("auth:menu")
    public String add() {
        return "user/add";
    }

    @RequestMapping("/user/update")
    @RequiresPermissions("auth:role")
    public String update() {
        return "user/update";
    }

    @RequestMapping("/login")
    public String login(String username, String password,Model model) {
        //获取当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        //根据用户名，密码封装成一个token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //验证登录
        try {
            subject.login(token);
            //登陆成功访问首页
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }

    @ResponseBody
    @RequestMapping("/unAuthorized")
    public String unAuthorized() {
        return "您没有访问该页面的权限!!!";
    }
}
